package NWish
{
	import NWish.json.Json;
	import NWish.json.OrderDict;
	import NWish.properties.Properties;
	import NWish.properties.object3ds.Scene3DProperties;
	import NWish.properties.other.FileSystemProperties;
	
	import NWish.Interface.IApp;
	import NWish.Interface.ILogger;
	
	import away3d.containers.Scene3D;
	import away3d.entities.Mesh;
	import away3d.events.AssetEvent;
	import away3d.events.LoaderEvent;
	import away3d.library.AssetLibrary;
	import away3d.library.assets.AssetType;
	import away3d.loaders.misc.AssetLoaderToken;
	import away3d.loaders.parsers.*;
	
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.Loader;
	import flash.events.*;
	import flash.net.*;
	import flash.ui.Keyboard;
	import flash.utils.ByteArray;
	
	import org.aswing.JMenuItem;
	import org.aswing.JOptionPane;
	import org.aswing.JSeparator;
	import org.aswing.KeySequence;
	import org.aswing.KeyStroke;
	import org.aswing.event.AWEvent;
	
	
	public class FileSystemEdit extends FileSystem
	{
		
		public function FileSystemEdit(app)
		{
			//
			super(app);
			
			
			//
			var menuBar:MenuBar = _app.getPlugin('MenuBar') as MenuBar;
			menuBar.settingMenu.addMenuItem("&File System setting").addActionListener(_showSetting);
			
			
			var mi:JMenuItem = menuBar.fileMenu.addMenuItem("&New");
			mi.addActionListener(actionNew);
			
			mi = menuBar.fileMenu.addMenuItem("&Open");
			mi.addActionListener(actionOpen);
			
			mi = menuBar.fileMenu.addMenuItem("&Import");
			mi.addActionListener(actionImport);
			
			menuBar.fileMenu.append(new JSeparator(JSeparator.HORIZONTAL));
			
			mi = menuBar.fileMenu.addMenuItem("&Save");
			mi.setAccelerator(new KeySequence(KeyStroke.VK_SHIFT, KeyStroke.VK_S));
			mi.addActionListener(actionSave);
			
			mi = menuBar.fileMenu.addMenuItem("Save Select as");
			mi.addActionListener(actionSaveSelectAs);
			
			menuBar.fileMenu.append(new JSeparator(JSeparator.HORIZONTAL));
			
			mi = menuBar.fileMenu.addMenuItem("&Add Resource");
			mi.addActionListener(actionAddResource);
			
			mi = menuBar.fileMenu.addMenuItem("&Remove Resource");
			mi.addActionListener(actionRemoveResource);
			
			
			
			//
			_app.rootSprite.stage.addEventListener(KeyboardEvent.KEY_UP, 		onKeyUp);
			
			//
			_app.rootSprite.addEventListener(NWEvent.SELSCT_OBJECT,	onSelectObject);
			//_app.rootSprite.addEventListener(NWEvent.CLEAR_SCENE,	onClearScene);
		}

		
		private function onKeyUp(e:KeyboardEvent) : void
		{
			//if(e.target != _app.rootSprite.stage)
			//	return;
			
			if(e.shiftKey && e.keyCode == Keyboard.S)
			{
				actionSave(null);
			}
		}
		
		private function actionNew(e:AWEvent) : void
		{
			if(view)
			{
				var p:JOptionPane = JOptionPane.showMessageDialog
					('Tips','Are sure to new a scene?'
						,newScene
						,null
						,true
						,null
						,JOptionPane.OK | JOptionPane.NO);
			}
			else
				newScene();
		}
		
		public function newScene(e = 1/*JOptionPane.OK*/)
		{
			if(e == JOptionPane.OK)
			{
				sceneName = 'unknow_scene';
				//_resourcePath = '';
				extra = null;
				
				_app.rootSprite.dispatchEvent(new NWEvent(NWEvent.CLEAR_SCENE,null/*,NWEvent.CREATE_VIEW*/));
				_app.rootSprite.dispatchEvent(new NWEvent(NWEvent.NEW_SCENE,null/*,NWEvent.CREATE_VIEW*/));
			}
		}
		
		
		private var _openFile:FileReference;
		private function actionOpen(e:AWEvent) : void
		{
			if(scene == null || scene.numChildren > 0)
			{
				JOptionPane.showMessageDialog('Tips','please new a scene first! MenuBar->File->New');
				return;
			}
			
			_openFile = new FileReference();
			_openFile.addEventListener(Event.COMPLETE, onOpenFile);
			_openFile.addEventListener(IOErrorEvent.IO_ERROR, Misc.ioErrorHandler);
			_openFile.addEventListener(SecurityErrorEvent.SECURITY_ERROR, Misc.securityErrorHandler);
			_openFile.addEventListener(Event.SELECT, selectHandler);
			_openFile.browse([new FileFilter("Scene Files (*.scene,*.json)", "*.scene;*.json")]);
		}
		
		private var _importFile:FileReference;
		private function actionImport(e:AWEvent) : void
		{
			_importFile = new FileReference();
			_importFile.addEventListener(Event.COMPLETE, onImportFile);
			_importFile.addEventListener(IOErrorEvent.IO_ERROR, Misc.ioErrorHandler);
			_importFile.addEventListener(SecurityErrorEvent.SECURITY_ERROR, Misc.securityErrorHandler);
			_importFile.addEventListener(Event.SELECT, selectHandler);
			_importFile.browse([new FileFilter("Scene Files (*.scene,*.json)", "*.scene;*.json")]);
		}
		private function actionSave(e:AWEvent) : void
		{
			var saveFile = new FileReference();
			saveFile.addEventListener(IOErrorEvent.IO_ERROR, Misc.ioErrorHandler);
			saveFile.addEventListener(SecurityErrorEvent.SECURITY_ERROR, Misc.securityErrorHandler);
			saveFile.save(getSceneJson(),sceneName + _sceneExtension);
		}
		private function actionSaveSelectAs(e:AWEvent) : void
		{
			var saveFile = new FileReference();
			saveFile.addEventListener(IOErrorEvent.IO_ERROR, Misc.ioErrorHandler);
			saveFile.addEventListener(SecurityErrorEvent.SECURITY_ERROR, Misc.securityErrorHandler);
			
			var json = getSelectJson();
			if(json)
				saveFile.save(json,_objectExtension);
		}
		var _addRes:FileReferenceList
		private function actionAddResource(e:AWEvent) : void
		{
			_addRes = new FileReferenceList();
			_addRes.addEventListener(Event.SELECT, selectHandler);
			_addRes.browse([new FileFilter
				("resource file (*.scene,*.json,*.jpg,*.png,*.md5mesh,*.md5anim,*.obj,*.3ds,*.ac,*.awd,*.md2,*.mp3)"
					,"*.scene;*.json;*.jpg;*.png;*.md5mesh;*.md5anim;*.obj;*.3ds;*.ac;*.awd;*.md2;*.mp3")]);
		}
		
		private function actionRemoveResource(e:AWEvent) : void
		{
			removeResource();
		}
		
		
		private function _showSetting(e)
		{
			_app.getPlugin('PropertiesExplorer')
				.setOtherObject(this,new FileSystemEditProperties(_app));
		}
		
		
		//
		private function onOpenFile(e:Event):void
		{
			//
			sceneName = 'unknow_scene';
			//_resourcePath = '';
			extra = null;
			_app.rootSprite.dispatchEvent(new NWEvent(NWEvent.CLEAR_SCENE,null));
			
			
			//
			//ILogger.log('todo onOpenFile ...');
			sceneName = _openFile.name.replace(_sceneExtension,'');
			
			//
			var json:String = _openFile.data.readUTFBytes(_openFile.data.bytesAvailable);
			
			var dict:Object = Json.decode( json,false );
			
			new FileSystemEditProperties(_app).load(dict,this,null,null);
			
			//
			_openFile = null;
		}
		private function onImportFile(e:Event):void
		{
			//
			var json:String = _importFile.data.readUTFBytes(_importFile.data.bytesAvailable);
			
			var dict:Object = Json.decode( json,false );
			
			if(dict['FileSystem'])
				new FileSystemEditProperties(_app,true).load(dict,this,null,null);
			else
			{
				for (var k:String in dict)
				{
					new Scene3DProperties(_app).loadObject3D(k,dict[k],scene);
				}
			}
			
			//
			_importFile = null;
		}
		/*private function onImportFile(e:Event):void
		{
			//
			var json:String = _importFile.data.readUTFBytes(_importFile.data.bytesAvailable);
			
			var dict:Object = Json.decode( json,false );
			
			for (var k:String in dict)
			{
				new Scene3DProperties(_app).loadObject3D(k,dict[k],scene);
			}
			
			_importFile = null;
		}*/
		
		private function selectHandler(e:Event):void
		{
			if(e.target == _openFile)
			{
				ILogger.log("open scene file : " + _openFile.name);
				_openFile.load();
			}
			else if(e.target == _importFile)
			{
				ILogger.log("import scene file : " + _importFile.name);
				_importFile.load();
			}
			else if(e.target == _addRes)
			{
				//
				var ps:Array = getPaths();
				if(ps.length == 0)
					ps = ['assets'];
				resourcePathSelect(onComplete,ps);
				
				function onComplete(resourcePath)
				{
					ILogger.log("add resource count : " + _addRes.fileList.length + " files");
					
					for (var i:uint = 0; i < _addRes.fileList.length; i++)
					{
						var file:FileReference = FileReference(_addRes.fileList[i]);
						addFile(file,resourcePath);
					}
				}
			}
		}
		
		private function addFile(file:FileReference,resourcePath):void
		{
			
			function onReadFile(e:Event):void
			{
				var file:FileReference = e.target as FileReference;
				
				//
				addFileData(file.name,resourcePath,file.data);
			}

			file.addEventListener(Event.COMPLETE, onReadFile);
			file.addEventListener(IOErrorEvent.IO_ERROR, Misc.ioErrorHandler);
			file.addEventListener(SecurityErrorEvent.SECURITY_ERROR, Misc.securityErrorHandler);
			file.load();
		}
		
		
		private function getSceneJson()
		{
			var sceneDict:OrderDict = new OrderDict();
			
			new FileSystemEditProperties(_app).save(this,sceneDict);
			
			return Json.encode( sceneDict );
		}
		
		private function getSelectJson()
		{
			if(_selectObjs == null)
			{
				ILogger.log('please select a object!');
				return;
			}
			
			if(_selectObjs is Array && _selectObjs.length > 1)
			{
				ILogger.log('please select object once!');
				return;
			}
			
			var obj = _selectObjs;
			if(obj is Array)
				obj = obj[0];
			
			//
			var dict:OrderDict = new OrderDict();
			
			new Scene3DProperties(_app).saveObject3D(obj,dict);
			
			return Json.encode( dict );
		}
		
		private var _selectObjs;
		private function onSelectObject(e:NWEvent)
		{
			_selectObjs = e.objects;
		}
		
	}
	
}


import NWish.FileSystem;
import NWish.properties.other.FileSystemProperties;


class FileSystemEditProperties extends FileSystemProperties 
{
	public function FileSystemEditProperties(parent,isImport = false)
	{
		super(parent,isImport);
	}
	
	override public function isClass(obj)
	{
		return obj is FileSystem;
	}
	
}


import org.aswing.JFrame;
import org.aswing.JComboBox;
import org.aswing.JPanel;
import org.aswing.JButton;
import flash.events.Event;
import org.aswing.EmptyLayout;

var resourcePathSelectFrame:JFrame;
function resourcePathSelect(onComplete,defaultPaths)
{
	if(resourcePathSelectFrame == null)
	{
		var frame:JFrame = new JFrame(null,"resource path", true);
		
		var pane:JPanel = new JPanel();
		pane.setLayout(new EmptyLayout());
		frame.setContentPane(pane);
		
		var paths:Array = defaultPaths;
		var cb:JComboBox = new JComboBox(paths);
		cb.setSelectedIndex(0);
		cb.setEditable(true);
		cb.setY(10);
		cb.setWidth(100);
		cb.setHeight(25);
		pane.append(cb);
		
		var ok:JButton = new JButton('OK');
		ok.setX(115);
		ok.setY(10);
		ok.setWidth(40);
		ok.setHeight(25);
		ok.addActionListener(onOK);
		pane.append(ok);
		
		resourcePathSelectFrame = frame;
		
		function onOK(e:Event)
		{
			resourcePathSelectFrame.visible = false;
			
			//
			var path = cb.getSelectedItem();
			if(paths.indexOf(path) == -1)
				paths.push(path);
			cb.setListData(paths);
			
			//
			onComplete(path);
		}
	}
	
	resourcePathSelectFrame.setComBoundsXYWH(150, 150, 175, 75);
	resourcePathSelectFrame.show();
	
}